//
//  ProductDetailTableViewController.m
//  FloatClouds
//
//  Created by 黄威 on 16/9/9.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "ProductDetailTableViewController.h"
#import "HWLNetworkTool.h"
#import "ProductModel.h"
#import "ProductComments.h"
#import "ProductDetailCell1.h"
#import "UIImageView+WebCache.h"
#import "ProductDetailCell2.h"
#import "BaseButton.h"
#import "SectionHeadView.h"
#import "ProductDetailCell3.h"
#import "SectionHeadView2.h"
#import "ProductDetailCell4.h"
#import "ProductComments.h"
#import "ProductDetailCell5.h"
#import "BaseButton.h"
#import "ProductCommentGetMore.h"
#import "GradeViewController.h"
#import "ProductMyComment.h"
#import "ProductAllImageViewController.h"
#import <sqlite3.h>
#import "FMDB.h"
#import "UMSocialWechatHandler.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "SVProgressHUD.h"


@interface ProductDetailTableViewController ()<UMSocialUIDelegate>
@property (nonatomic, retain) ProductModel *productModel;
@property (nonatomic, retain) NSArray *arrayOfTitle;
@property (nonatomic, assign) CGSize widthAndHeight;
@property (nonatomic, retain) NSArray *arrayOfPhotoList;
@property (nonatomic, retain) FMDatabase *db;
@property (nonatomic, retain) UIView *whiteView;
@property (nonatomic, retain) UIImage *shareImage;

@end

@implementation ProductDetailTableViewController



- (void)viewDidLoad{

   
    
    UIBarButtonItem *btn1 = [[UIBarButtonItem alloc]initWithTitle:@"评分" style:UIBarButtonItemStylePlain target:self action:@selector(grade)];
    UIBarButtonItem *btn2 = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(collect)];
    UIBarButtonItem *btn3 = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    [btn2 setTintColor:[UIColor whiteColor]];
    [btn3 setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItems = @[btn1,btn2,btn3];
    
    
    
    [self.tableView registerClass:[ProductDetailCell1 class] forCellReuseIdentifier:@"ProductDetailCell1"];
    [self.tableView registerClass:[ProductDetailCell2 class] forCellReuseIdentifier:@"ProductDetailCell2"];
    [self.tableView registerClass:[ProductDetailCell3 class] forCellReuseIdentifier:@"ProductDetailCell3"];
    [self.tableView registerClass:[ProductDetailCell4 class] forCellReuseIdentifier:@"ProductDetailCell4"];
    [self.tableView registerClass:[ProductDetailCell5 class] forCellReuseIdentifier:@"ProductDetailCell5"];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tabBarController.tabBar.hidden=YES;
    self.arrayOfTitle = @[@"  名烟鉴赏",@"  各项评分",@"  产品图片",@"  其他参数",@"  网友评论",@"la"];
    
    [self createNavigationItem];
    [self handData];
    
    
    self.whiteView = [[UIView alloc]initWithFrame:self.view.bounds];
    self.whiteView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.1];
    
    //全屏遮盖View
    [[UIApplication sharedApplication].keyWindow addSubview:self.whiteView];

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.whiteView removeFromSuperview];

    });
    
}

- (void)createNavigationItem{
    
    
    //设置navigation相关属性
    
   
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"名烟详情";
   
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
}


- (void)handData{

    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // time-consuming task
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [SVProgressHUD showWithStatus:@"加载中..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD setForegroundColor:[UIColor grayColor]];
            [SVProgressHUD setMinimumDismissTimeInterval:3];
            
        });
    });
   NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    NSString *body = [@"ID="stringByAppendingString:self.productId];

    
    [HWLNetworkTool POST:@"http://app.yanyue.cn/product/detail" andBody:body andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
        
        
        
        self.productModel = [ProductModel modelWithDic:result];
        
    
        self.arrayOfPhotoList = self.productModel.photolist;
      
        [self.tableView reloadData];
        
        
        [self.whiteView removeFromSuperview];

        [SVProgressHUD dismiss];
        
    } andFailureBlock:^(NSError *error) {
        
    }];



}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 6;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return 1;
    }
    if (section == 2) {
        return 0;
    }if (section == 3){
        return 1;
    }if (section == 4) {
        return self.productModel.comments.count;
    }if (section == 5) {
        return 1;
    }
    return 0;
}

- (void)longpress:(UITapGestureRecognizer *)longpress{



}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    if (indexPath.section == 0) {
        ProductDetailCell1 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ProductDetailCell1" forIndexPath:indexPath];
        NSURL *url = [NSURL URLWithString:self.productModel.photo];
        [cell.image sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placrholder"]];
        
      
        
        self.shareImage = cell.image.image;
        
        int score = self.productModel.score;
        cell.score.text = [NSString stringWithFormat:@"%d",score];
        cell.name.text = self.productModel.name;
        
        cell.imageView.userInteractionEnabled = YES;
        self.view.userInteractionEnabled = YES;
        cell.userInteractionEnabled = YES;
        UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longpress:)];
        longpress.minimumPressDuration = 0.2;
        [cell.imageView addGestureRecognizer:longpress];
        
        
        return cell;
        
    }
    
    
    
    if (indexPath.section == 1) {
        ProductDetailCell2 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ProductDetailCell2" forIndexPath:indexPath];
        CGFloat score = self.productModel.score;
        cell.labelOfScoreInput.text = [NSString stringWithFormat:@"%0.1f",score];
        cell.labelOfPriceInput.text = self.productModel.price;
        CGFloat taste = self.productModel.taste_grade;
        cell.labelOftasteInput.text = [NSString stringWithFormat:@"%0.1f",taste];
        CGFloat view = self.productModel.appearance_grade;
        cell.labelOfViewInput.text = [NSString stringWithFormat:@"%0.1f",view];
        CGFloat cost = self.productModel.cost_performance;
        cell.labelOfCostPerformanceInput.text = [NSString stringWithFormat:@"%0.1f",cost];
        
        return cell;
        
    }
    if (indexPath.section == 3) {
        
        ProductDetailCell3 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ProductDetailCell3" forIndexPath:indexPath];
        cell.labelOftypeInput.text = self.productModel.type;
        cell.tarInput.text = self.productModel.tar_conten;
        cell.nicoInput.text = self.productModel.nicotine_content;
        cell.cigarettelongInput.text = self.productModel.cigarette_length;
        cell.packingInput.text = self.productModel.appearance;
        cell.numberInput.text = self.productModel.num_per_box;
        cell.productStausInput.text = self.productModel.product_status;
        cell.coInput.text = self.productModel.co_content;
        
        return cell;
    }
    if
    (indexPath.section == 4){
        
        
        [self height:self.productModel.comments[indexPath.row].content];
        
        ProductDetailCell4 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ProductDetailCell4" forIndexPath:indexPath];
        cell.name.text = self.productModel.comments[indexPath.row].name;
        cell.time.text = self.productModel.comments[indexPath.row].time;
        cell.landname.text = self.productModel.comments[indexPath.row].province;
        cell.priceInput.text = self.productModel.comments[indexPath.row].local_price;
        cell.content.text = self.productModel.comments[indexPath.row].content;
        cell.widthAndHeight = self.widthAndHeight;
        return cell;
    }
    if ( indexPath.section == 5) {
        
        ProductDetailCell5 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ProductDetailCell5" forIndexPath:indexPath];
     
        [cell.button addTarget:self action:@selector(say) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
        
    }
    

    return 0;

    
}


- (void)height:(NSString *)str{

    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetica" size:17],NSFontAttributeName, nil];
    
    UILabel *label = [[UILabel alloc]init];
    label.numberOfLines = 0;
    label.text = str;
    
   self.widthAndHeight = [label.text boundingRectWithSize:CGSizeMake(self.view.bounds.size.width - 30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;


}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0 ) {
        
        
        return self.view.bounds.size.width *0.8;
    }
    if (indexPath.section == 1){
    
        return  self.view.bounds.size.width *0.4;
    }if (indexPath.section == 2) {
        return 0;
    }
    
    if (indexPath.section == 3) {
        return  self.view.bounds.size.width * 0.6;
    }
    if (indexPath.section == 4) {
        
        return self.widthAndHeight.height + 90;
    } if (indexPath.section == 5) {
        return  self.view.bounds.size.width *0.2;
    }

    return 0;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    return self.arrayOfTitle[section];



}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    if (section == 0) {
        return 0;
    }
    
    if (section == 2) {
        return 30;
    }
    if (section == 3) {
        return 30;
    }
    if(section == 4){
        return 30;
    }if (section == 5)
    {
        return 0;
    }
    return self.view.bounds.size.width *0.1;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section == 2) {
        
        SectionHeadView *headview = [[SectionHeadView alloc]init];
        headview.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width *0.2);

        [headview.button addTarget:self action:@selector(lookMore) forControlEvents:UIControlEventTouchUpInside];
        return headview;
          }
    
    if(section == 4){
    
        SectionHeadView2 *headview2 = [[SectionHeadView2 alloc]init];
        headview2.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width *0.2);
        
        [headview2.button addTarget:self action:@selector(lookMore2) forControlEvents:UIControlEventTouchUpInside];
        return headview2;

    }

    return nil;
}


- (void)say{

    ProductMyComment *comment = [[ProductMyComment alloc]init];
    comment.productID = self.productId;
    [self.navigationController pushViewController:comment animated:YES];
    
}

- (void)lookMore{

    ProductAllImageViewController *allPhotoViewController = [[ProductAllImageViewController alloc]init];
    
    allPhotoViewController.arrayOfListPhoto = self.arrayOfPhotoList;
    
    [self.navigationController pushViewController:allPhotoViewController animated:YES];
    
   

}

- (void)lookMore2{

    
    ProductCommentGetMore *getMore2 = [[ProductCommentGetMore alloc]init];
    
    getMore2.productId = self.productId;
    
    [self.navigationController pushViewController:getMore2 animated:YES];
    

}

- (void)grade{
    
    GradeViewController *grade = [[GradeViewController alloc]init];
    
    grade.productID = self.productId;
    
    [self.navigationController pushViewController:grade animated:YES];

}


- (void)collect{
  
    
    NSString *photo = self.productModel.photo;
   
    NSString *name = self.productModel.name;
    
    CGFloat score1 = self.productModel.score;
    NSString *score = [NSString stringWithFormat:@"%0.1f",score1];
    
    NSString *price = self.productModel.price;

    NSString *productID = self.productId;
    
  
   
    
    
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;


     NSString *sqlFilePath = [documentPath stringByAppendingPathComponent:@"cigarette.sqlite"];
    
    self.db = [FMDatabase databaseWithPath:sqlFilePath];
    if ([self.db open]) {
        NSLog(@"打开成功");
        
        NSString *sqlCreateStr = [NSString stringWithFormat:@"create table if not exists cigaretteCollect(number integer primary key autoincrement, name text, score text, price text,productID text, photo text)"];
        
        BOOL success = [self.db executeUpdate:sqlCreateStr];
        
        if (success) {
            NSLog(@"创建表成功");
        } else {
            NSLog(@"创建表失败");
        }
        } else {
        NSLog(@"打开失败");
         }
 
    NSString *insertStr = [NSString stringWithFormat:@"INSERT INTO cigaretteCollect (name,score,price,productID,photo) VALUES ('%@','%@','%@','%@','%@');",name,score,price,productID,photo];
 
    BOOL success = [self.db executeUpdate:insertStr];
    if (success) {
        NSLog(@"插入成功");
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
          
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        
    } else {
        NSLog(@"插入失败");
    }
       
    
}


- (void)share{
    
    
    
    NSString *string1 = @"我用浮云APP在大宇哥家找到了( ";
    NSString *string2 = self.productModel.name;
    NSString *string3 = @" )香烟的详细资料,还有真伪鉴别和品吸测评,很不错的App,值得一看!,推荐!!!";
    
    NSString *string4 = [[string1 stringByAppendingString:string2]stringByAppendingString:string3];
    
    
    
    
    
    [UMSocialData defaultData].extConfig.title = string4;
    [UMSocialData defaultData].extConfig.wechatSessionData.url  = @"http://user.qzone.qq.com/692382667";
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = @"http://user.qzone.qq.com/692382667";
    [UMSocialData defaultData].extConfig.wechatFavoriteData.url = @"http://user.qzone.qq.com/692382667";
    [UMSocialData defaultData].extConfig.qqData.url = @"http://user.qzone.qq.com/692382667";
    
    
    
    
   // NSLog(@"%@",self.shareImage);
    
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"57e3a06a67e58e9ed90006fa"
                                      shareText:@"FloatClouds APP"
                                     shareImage:self.shareImage
                                shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone]
                                       delegate:self];
    
}

-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}


- (void)viewDidDisappear:(BOOL)animated{

    [super viewDidDisappear:animated];
    
    [self.db close];

}

@end
